package com.heima.behavior.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.dto.ArticleInfoDtoV2;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.UnlikesBehaviorDtoV2;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.entity.ApUnlikesBehaviorV2;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapperV2;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApUnlikesBehaviorServiceV2;
import com.heima.common.dto.ResponseResult;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP不喜欢行为表 服务实现类
 * </p>
 *
 * @author changjiang
 * @since 2022-03-18
 */
@Service
public class ApUnlikesBehaviorServiceImplV2 extends ServiceImpl<ApUnlikesBehaviorMapperV2, ApUnlikesBehaviorV2> implements IApUnlikesBehaviorServiceV2 {

    @Autowired
    private IApBehaviorEntryService entryService;




    @Override
    public ResponseResult unlikesBehavior0(UnlikesBehaviorDtoV2 dto) {
        EntryDto entryDto = new EntryDto();
        entryDto.setUserId(AppThreadLocalUtil.get().getUserId());
        entryDto.setEquipmentId(dto.getEquipmentId());
        ApBehaviorEntry entry = entryService.getEntry(entryDto);
        dto.setEntryId(entry.getId());
        //查询该用户或设备有无对该文章的操作
        LambdaQueryWrapper<ApUnlikesBehaviorV2> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUnlikesBehaviorV2::getArticleId,dto.getArticleId()).eq(ApUnlikesBehaviorV2::getEntryId,dto.getEntryId());
        ApUnlikesBehaviorV2 apUnlikesBehavior = getOne(queryWrapper);
        if(apUnlikesBehavior==null) {
            apUnlikesBehavior = new ApUnlikesBehaviorV2();
        }
        BeanUtils.copyProperties(dto,apUnlikesBehavior);
        apUnlikesBehavior.setType(dto.getType());
        if (apUnlikesBehavior.getId()==null)
            apUnlikesBehavior.setCreatedTime(new Date());
       saveOrUpdate(apUnlikesBehavior);

        return ResponseResult.okResult();
    }

    @Override
    public boolean isUnlike(ArticleInfoDtoV2 dto) {

        Integer entryId;
        entryId = (dto.getUserId());
        LambdaQueryWrapper<ApUnlikesBehaviorV2> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUnlikesBehaviorV2::getArticleId,dto.getArticleId()).eq(ApUnlikesBehaviorV2::getEntryId,entryId);
        ApUnlikesBehaviorV2 apUnlikesBehaviorV2 = getOne(queryWrapper);
        return apUnlikesBehaviorV2!=null&&apUnlikesBehaviorV2.getType()==0;
    }


}
